/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.aliyun.opensearch.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;


/**
 * 封装HTTPClient的工具类
 * 
 * @author liaoran.xg
 * 不在使用了，改为使用HttpClientManager
 * 
 */
@Deprecated
public class HttpClientUtil {
	private static HttpParams params;
	private static ClientConnectionManager cm;
	
  /**
   * 请求API的连接超时时间，单位为毫秒。
   */
  public static final int CONNECT_TIMEOUT = 30000;
  /**
   * 请求API的时间，单位为毫秒。
   */
  public static final int TIMEOUT = 30000;
	static {
		params = new BasicHttpParams();
//		params.setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000));
		ConnManagerParams.setTimeout(params, 30000);
		ConnManagerParams.setMaxTotalConnections(params, 100);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		cm = new ThreadSafeClientConnManager(params, schemeRegistry);

	}

	public static HttpClient getHttpclient() {
		return new DefaultHttpClient(cm, params);
	}

	public static boolean doStatusGet(String url) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		HttpGet httpget = new HttpGet(url);
		HttpResponse res = httpclient.execute(httpget);
		return res.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
	}

	public static InputStream doGet(String url, boolean gzip) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		HttpGet httpget = new HttpGet(url);
		if (gzip) {
			httpget.setHeader("Accept-Encoding", "gzip");
		}
		HttpResponse res = httpclient.execute(httpget);
		InputStream in = null;
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			in = res.getEntity().getContent();
		} else {
			httpget.abort();
		}
		
		if (gzip) {
			return  new GZIPInputStream(in);
		}
		return in;
	}

	public static InputStream doPost(String url, Map<String, String> m, String encoding, boolean gzip) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		HttpPost httpost = new HttpPost(url);
		
		if (gzip) {
			httpost.setHeader("Accept-Encoding", "gzip");
		}
		
		httpost.setEntity(new UrlEncodedFormEntity(getNameValuePair(m), encoding));
		HttpResponse res = httpclient.execute(httpost);
		InputStream in = null;
		
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			in = res.getEntity().getContent();
		} else {
			httpost.abort();
		}
		
		if (gzip) {
			return  new GZIPInputStream(in);
		}
		return in;
	}

	public static InputStream doPost(String url, Map<String, String> m, boolean gzip) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		
		HttpPost httpost = new HttpPost(url);
		
		if (gzip) {
			httpost.setHeader("Accept-Encoding", "gzip");
		}
		httpost.setEntity(new UrlEncodedFormEntity(getNameValuePair(m)));
		HttpResponse res = httpclient.execute(httpost);
		InputStream in = null;
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			in = res.getEntity().getContent();
		} else {
			httpost.abort();
		}
		if (gzip) {
			return  new GZIPInputStream(in);
		}
		return in;
	}

	public static InputStream doPost(String url, Map<String, String> m, File file) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		HttpPost httpost = new HttpPost(url);
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
		entityBuilder.addBinaryBody("fileBody", file);
		
		if (m != null && m.size() > 0) {
			for (Entry<String, String> entry : m.entrySet()) {
				entityBuilder.addTextBody(entry.getKey(), entry.getValue());
			}
		}
		
		HttpEntity reqEntity = entityBuilder.build();
		
		httpost.setEntity(reqEntity);
		
		HttpResponse res = httpclient.execute(httpost);
		InputStream in = null;
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity resEntity = res.getEntity();
			if (resEntity != null) {
				in = resEntity.getContent();
			}
		} else {
			httpost.abort();
		}
		return in;
	}

	public static String post(String url, Map<String, String> m, String paramEncoding, String encoding, boolean gzip) throws ClientProtocolException, IOException {
		return toString(doPost(url, m, paramEncoding, gzip), encoding);
	}

	public static String post(String url, Map<String, String> m, String paramEncoding) throws ClientProtocolException, IOException {
		return toString(doPost(url, m, paramEncoding, false));
	}

	public static String post(String url, Map<String, String> m) throws ClientProtocolException, IOException {
		return toString(doPost(url, m, false));
	}

	public static String post(String url, Map<String, String> m, File file) throws ClientProtocolException, IOException {
		return toString(doPost(url, m, file));
	}

	public static String get(String url, String encoding, boolean gzip) throws ClientProtocolException, IOException {
		return toString(doGet(url, gzip), encoding);
	}

	public static String get(String url) throws ClientProtocolException, IOException {
		return toString(doGet(url, false));
	}

	public static String toString(InputStream is, String encoding) throws IOException {
		String content = null;
		try {
			if (is != null) {
				content = IOUtils.toString(is, encoding);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return content;
	}

	public static String toString(InputStream is) throws IOException {
		String content = null;
		try {
			if (is != null) {
				content = IOUtils.toString(is);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return content;
	}

	public static List<NameValuePair> getNameValuePair(Map<String, String> m) {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (String k : m.keySet()) {
			NameValuePair v = new BasicNameValuePair(k, m.get(k));
			list.add(v);
		}
		return list;
	}
	
	public static InputStream doDelete(String url) throws ClientProtocolException, IOException {
		
		HttpClient httpclient = new DefaultHttpClient(cm, params);
		HttpDelete httpdelete = new HttpDelete(url);
		HttpResponse res = httpclient.execute(httpdelete);
		InputStream in = null;
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			in = res.getEntity().getContent();
		} else {
			httpdelete.abort();
		}
		return in;
	}
	
	public static String delete(String url) throws ClientProtocolException, IOException {
		return toString(doDelete(url));
	}

	public static void main(String[] s) throws ClientProtocolException, IOException {
		//String sss = get("http://www.taobao.com");
		//System.out.print(sss);
	}
}
